package com.lm.authorization.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;


@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {

    @Bean
    public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity (http);
        http.getConfigurer (OAuth2AuthorizationServerConfigurer.class)
                //启用OpenID Connect 1.0
                .oidc (Customizer.withDefaults ());
        http
                // 未从授权端点进行身份验证时重定向到登录页面
                .exceptionHandling ((exceptions) -> exceptions
                        .defaultAuthenticationEntryPointFor (
                                new LoginUrlAuthenticationEntryPoint ("/login"),
                                new MediaTypeRequestMatcher (MediaType.TEXT_HTML)
                        )
                )
                //接受用户信息和/或客户端注册的访问令牌
                .oauth2ResourceServer ((resourceServer) -> resourceServer
                        .jwt (Customizer.withDefaults ()));

        return http.build ();
    }

    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests ((authorize) -> authorize
                        .requestMatchers (new AntPathRequestMatcher ("/actuator/**"),
                                new AntPathRequestMatcher ("/oauth2/**"),
                                new AntPathRequestMatcher ("/**/*.json"),
                                new AntPathRequestMatcher ("/**/*.css"),
                                new AntPathRequestMatcher ("/**/*.html")).permitAll ()
                        .anyRequest ().authenticated ()
                )
                .formLogin (Customizer.withDefaults ());
        return http.build ();
    }
}
